<template>
  <div class="medication-container">
    <div class="vertical-warning">这不是病史，而是我的来时路</div>
    <h3><i class="fas fa-pills"></i> 既往病史</h3>
    <div v-if="isSampleData" class="sample-notice">
      <el-icon>
        <info-filled/>
      </el-icon>
      当前显示为示例数据，请登录后查看真实记录
    </div>


    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          v-if="!editMode"
          type="primary"
          @click="editMode = true"
          icon="el-icon-edit"
          class="action-btn"
      >编辑
      </el-button>
      <el-button
          v-if="!editMode"
          type="success"
          @click="addNewHistory"
          icon="el-icon-plus"
          class="action-btn"
      >新增
      </el-button>
      <el-button
          v-if="!editMode"
          type="warning"
          @click="toggleSort"
          icon="el-icon-sort"
          class="action-btn"
      >{{ sortButtonText }}
      </el-button>
      <template v-else>
        <el-button
            type="success"
            @click="saveChanges"
            icon="el-icon-check"
            class="confirm-btn"
        >保存
        </el-button>
        <el-button
            type="danger"
            @click="cancelEdit"
            icon="el-icon-close"
            class="cancel-btn"
        >取消
        </el-button>
      </template>
    </div>

  <div class="medication-list">
    <div
        class="medication-card"
        :class="{ 'sample-data': isSampleData }"
        v-for="(history, index) in medicalHistories"
        :key="history.recordId || index"
        @mousedown="createRipple"
    >
      <div class="medication-header">
        <span class="detail-label"><i class="far fa-clock"></i> ID:{{ history.recordId }}</span>
        <span class="detail-label"><i class="far fa-clock"></i> 疾病名称:</span>
        <div class="medication-name">
          <span v-if="!editMode"><i class="fas fa-disease"></i> {{ history.diseaseName }}</span>
          <input v-else v-model="history.diseaseName" class="form-input" placeholder="疾病名称">
        </div>
        <div class="medication-status" v-if="!editMode">
          <i class="far fa-calendar-alt"></i> {{ history.recordDate }}
        </div>
      </div>

      <div class="medication-details">
        <div class="detail-row">
          <span class="detail-label"><i class="fas fa-notes-medical"></i> 症状描述:</span>
          <span v-if="!editMode">{{ history.symptoms }}</span>
          <input v-else v-model="history.symptoms" class="form-input" placeholder="症状描述">
        </div>

        <div class="detail-row">
          <span class="detail-label"><i class="fas fa-search"></i> 病因:</span>
          <span v-if="!editMode">{{ history.cause }}</span>
          <input v-else v-model="history.cause" class="form-input" placeholder="病因">
        </div>

        <div class="detail-row">
          <span class="detail-label"><i class="fas fa-procedures"></i> 治疗过程:</span>
          <span v-if="!editMode">{{ history.treatmentProcess }}</span>
          <input v-else v-model="history.treatmentProcess" class="form-input" placeholder="治疗过程">
        </div>

        <div class="detail-row">
          <span class="detail-label"><i class="fas fa-exclamation-triangle"></i> 后遗症:</span>
          <span v-if="!editMode">{{ history.hasSequel }}</span>
          <input v-else v-model="history.hasSequel" class="form-input" placeholder="是否有后遗症">
        </div>
      </div>

      <!-- 删除按钮放在每张卡片内 -->
      <div class="card-actions" v-if="editMode">
        <el-button
            type="danger"
            size="small"
            @click="deleteHandler(index)"
            icon="el-icon-delete"
        >删除
        </el-button>
      </div>
    </div>
  </div>


  <!-- 分页控件 -->
  <div class="pagination-controls">
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalRecords"
        :page-sizes="[1,2,4,8,10, 20, 30, 50]"
        layout="sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"


        @current-change="handlePageChange"
    />
  </div>

  <!-- 升级后的弹出对话框 -->
  <div class="popup-container" :class="{ 'show-popup': showAddDialog }">
    <div class="popup-backdrop" @click="showAddDialog = false"></div>
    <div class="popup-dialog" :class="{ 'scale-in': showAddDialog }">
      <div class="popup-header">
        <div class="popup-title">
          <i class="fas fa-plus-circle header-icon"></i>
          <h3>新增病史记录</h3>
        </div>
        <button class="close-button" @click="showAddDialog = false">
          <i class="el-icon-close"></i>
        </button>
      </div>

      <el-form :model="currentHistory" label-width="110px" class="popup-form">

        <el-form-item label="记录时间：" disabled="disabled">
          <el-date-picker
              v-model="currentHistory.recordDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              class="custom-date-picker"
              :popper-class="'custom-date-popper'"
          />
        </el-form-item>

        <el-form-item label="疾病名称：" prop="medicationName">
          <el-input
              v-model="currentHistory.diseaseName"
              placeholder="请输入疾病名称"
              class="custom-input"
              suffix-icon="el-icon-document"
          />
        </el-form-item>

        <el-form-item label="症状：" prop="usageAndDosage">
          <el-input
              v-model="currentHistory.symptoms"
              placeholder="例如：呕吐腹泻"
              class="custom-input"
              suffix-icon="el-icon-timer"
          />
        </el-form-item>

        <el-form-item label="病因：" class="form-item-vertical">
          <el-input
              v-model="currentHistory.cause"
              placeholder="请输入病因"
              type="textarea"
              :rows="3"
              class="custom-textarea"
          />
        </el-form-item>

        <el-form-item label="治疗过程：" class="form-item-vertical">
          <el-input
              v-model="currentHistory.treatmentProcess"
              placeholder="请输入治疗过程"
              type="textarea"
              :rows="3"
              class="custom-textarea"
          />
        </el-form-item>

        <el-form-item label="后遗症：" class="form-item-vertical">
          <el-input
              v-model="currentHistory.hasSequel"
              placeholder="请输入后遗症情况"
              type="textarea"
              :rows="3"
              class="custom-textarea"
          />
        </el-form-item>


        <el-form-item label="备注：" class="form-item-vertical">
          <el-input
              v-model="currentHistory.remarks"
              placeholder="如有，请输入备注"
              type="textarea"
              :rows="3"
              class="custom-textarea"
          />
        </el-form-item>
      </el-form>

        <div class="popup-footer">
          <el-button
              class="custom-cancel-btn"
              @click="showAddDialog = false"
          >取消
          </el-button>
          <el-button
              type="primary"
              class="custom-confirm-btn"
              @click="saveNewMedication"
          >保存记录
          </el-button>
        </div>
      </div>
    </div>

    <div class="total-records-notice">
      <el-icon>
        <info-filled/>
      </el-icon>
      您共有{{ totalRecords }}条病史记录
    </div>
  </div>

</template>


<script setup>
import {computed, nextTick, onMounted, onUnmounted, reactive, ref} from 'vue';
import {createHealthRecord, deleteHealthRecord, getMedicalHistory, updateHealthRecord} from "@/api/profile.js";
import {ElButton, ElForm, ElFormItem, ElInput, ElMessage, ElMessageBox, ElPagination} from 'element-plus';
import {InfoFilled} from '@element-plus/icons-vue';
import {postLog} from "@/api/log.js";

// 响应式状态
const editMode = ref(false);
const showAddDialog = ref(false);
const currentHistory = reactive({
  recordId: null,
  recordDate: new Date().toISOString().split('T')[0],
  recordType: '既往病史',
  diseaseName: '',
  symptoms: '',
  cause: '',
  treatmentProcess: '',
  hasSequel:'',
  remarks:''
});
const medicalHistories = ref([]);
const originalMedications = ref([]);
const currentPage = ref(1);
const pageSize = ref(8);
const totalRecords = ref(0);
const isLoading = ref(false);
const isSampleData = ref(false);

const isSortedAscending = ref(true);
const sortButtonText = computed(() => isSortedAscending.value ? '按日期排序 ↑' : '按日期排序 ↓');

// 用户状态监听
const userInfo = ref(null);
const handleUserLogout = () => {
  userInfo.value = null;
  medicalHistories.value = [];
};

// 更新示例数据
const sampleHistories = ref([{
  recordId: 1,
  diseaseName: '糖尿病',
  symptoms: '多饮多尿',
  cause: '遗传因素',
  treatmentProcess: '胰岛素治疗',
  hasSequel: '无'
}]);

// 生命周期钩子
onMounted(async () => {
  try {
    const storedUser = localStorage.getItem('currentUser');
    userInfo.value = storedUser ? JSON.parse(storedUser) : null;
    await load();
  } catch (error) {
    console.error('初始化失败:', error);
  }

  window.addEventListener('user-logout', handleUserLogout);
  window.addEventListener('storage', (e) => {
    if (e.key === 'currentUser' && !e.newValue) handleUserLogout();
  });
});

onUnmounted(() => {
  window.removeEventListener('user-logout', handleUserLogout);
});

// 业务逻辑方法
const load = async () => {
  isLoading.value = true;
  try {
    const res = await getMedicalHistory(userInfo.value?.id, {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    isSortedAscending.value = !isSortedAscending.value;
    res.data.data.sort((a, b) => {
      return isSortedAscending.value
          ? a.recordDate.localeCompare(b.recordDate)
          : b.recordDate.localeCompare(a.recordDate);
    });
    if (res.data?.data) {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      medicalHistories.value = res.data.data.slice(startIndex, endIndex);
      totalRecords.value = res.data.total || res.data.data.length;
      originalMedications.value = JSON.parse(JSON.stringify(res.data.data));
      isSampleData.value = false;
    }
  } catch (error) {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    medicalHistories.value = sampleHistories.value.slice(startIndex, startIndex + pageSize.value);
    totalRecords.value = sampleHistories.value.length;
    isSampleData.value = true;
  } finally {
    isLoading.value = false;
  }
};

const addNewHistory = () => {
  console.log('新增按钮点击事件触发');
  Object.assign(currentHistory, {
    recordId: null,
    recordDate: new Date().toISOString().split('T')[0],
    recordType: '既往病史',
    diseaseName: '',
    symptoms: '',
    cause: '',
    treatmentProcess: '',
    hasSequel: '',
    remarks: ''
  });

  // 触发对话框显示并添加动画类
  nextTick(() => {
    showAddDialog.value = true;
  });
};

// 新增病史验证逻辑
const validateHistory = (history) => {
  if (!history.diseaseName?.trim()) {
    ElMessage.error('疾病名称不能为空');
    return false;
  }
  if (!history.symptoms?.trim()) {
    ElMessage.error('症状描述不能为空');
    return false;
  }
  return true;
};

const saveNewMedication = async () => {
  if (!validateHistory(currentHistory)) return;

  try {
    const submitData = {
      ...currentHistory,
      detail: `${currentHistory.diseaseName}|${currentHistory.symptoms}|${currentHistory.cause}|${currentHistory.treatmentProcess}|${currentHistory.hasSequel}|${currentHistory.remarks}|`
    };
    const response = await createHealthRecord(userInfo.value?.id, submitData);
    ElMessage.success('新增成功');
    showAddDialog.value = false;
    await load();

    // 新增操作日志记录
    if (userInfo.value) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '既往病史',
        action: '增加',
        recordId: response.data?.data,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }
  } catch (error) {
    ElMessage.error('新增失败：' + error.message);
  }
};

const saveChanges = async () => {
  if (medicalHistories.value.some(history => !validateHistory(history))) return;

  try {
    const promises = medicalHistories.value.map(async (history) => {
      const submitData = {
        recordId: history.recordId,
        recordDate: history.recordDate,
        recordType: '既往病史',
        detail: `${history.diseaseName}|${history.symptoms}|${history.cause}|${history.treatmentProcess}|${history.hasSequel}|${history.remarks}`
      };
      return history.recordId
          ? await updateHealthRecord(submitData)
          : await createHealthRecord(userInfo.value?.id, submitData);
    });

    await Promise.all(promises);
    ElMessage.success('保存成功');
    editMode.value = false;
    await load();

    // 新增操作日志记录
    if (userInfo.value) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '既往病史',
        action: '修改',
        recordId: history.recordId,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }
  } catch (error) {
    ElMessage.error('保存失败：' + error.message);
  }
};

const cancelEdit = () => {
  editMode.value = false;
  medicalHistories.value = JSON.parse(JSON.stringify(originalMedications.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)));

};

const deleteHandler = async (index) => {
  try {
    await ElMessageBox.confirm('确定删除该病史记录吗？', '提示', {
      confirmButtonText: '哦，当然',
      cancelButtonText: '删个屁',
      type: 'warning'
    });

    const recordId = medicalHistories.value[index].recordId;
    if (recordId) {
      await deleteHealthRecord(recordId);
    }
    medicalHistories.value.splice(index, 1);
    ElMessage.success('删除成功');

    if (medicalHistories.value.length === 0 && currentPage.value > 1) {
      currentPage.value--;
      await load();
    }
    // 删除操作日志记录
    if (userInfo.value && recordId) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '既往病史',
        action: '删除',
        recordId: recordId,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败：' + error.message);
  }
};

const handlePageChange = (page) => {
  currentPage.value = page;
  isSortedAscending.value = !isSortedAscending.value;

  load();
};
const handleSizeChange = (val) =>{
  currentPage.value=1;
  pageSize.value = val;
  load();
}
const toggleSort = () => {
  load();
};
</script>
<style scoped>
@import "@/assets/css/new.css";

</style>